<template>
  <div class="app-container">
    <Form
      v-if="showSearch"
      v-model:formData="searchInfo"
      :formItems="formItems"
    >
      <template #footer>
        <div style="text-align: left">
          <el-button size="small" icon="Search" type="primary" @click="goSearch"
            >搜索</el-button
          >
          <el-button size="small" icon="Refresh" @click="resetSearch"
            >重置</el-button
          >
        </div>
      </template>
    </Form>
    <h3>
      <el-button
        type="primary"
        @click="add"
        icon="Plus"
        size="small"
        v-hasPermi="['api:merchant:add']"
        >添加</el-button
      >
    </h3>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5"> </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="resetSearch"
      ></right-toolbar>
    </el-row>
    <h3></h3>
    <x-table
      :propList="propList"
      :tableData="info.items"
      :isLoading="isLoading"
    >
      <template #status="{ row }">
        <el-tag type="success" v-if="row.status == 1">启用</el-tag>
        <el-tag type="danger" v-else>禁用</el-tag>
      </template>
      <!-- <template #pay="{ row }">
        <el-select v-model="row.pay_id" @change="setPay($event,row)" placeholder="请选择">
          <el-option
            v-for="item in customerList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
      </el-select>
      </template> -->
      <template #poster="{ row }">
        <el-select v-model="row.share_sys_user_id" @change="setPoster($event,row)" placeholder="请选择">
          <el-option
            v-for="item in customerList"
            :key="item.id"
            :label="item.nickname"
            :value="item.id">
          </el-option>
      </el-select>
      </template>
      <template #is_main="{ row }">
      <el-tag v-if="row.is_main==1" type="success">是</el-tag>
      <el-tag v-else type="info">否</el-tag>
      </template>
      
      <template #create_time="{ row }">
        <span>{{ row.create_time }}</span
        ><br />
        <span>{{ row.update_time }}</span>
      </template>
      <template #group_name="{ row }">
        <span v-if="row.group_id">{{ row.group_name }}</span>
        <span v-else>无分组</span>
      </template>

      <template #op="{ row }">
        <el-button
          type="primary"
          link
          icon="Plus"
          @click="manage(row)"
          v-hasPermi="['api:merchant:manage']"
          >进入管理</el-button
        >
        <el-button
          type="primary"
          link
          icon="Edit"
          @click="mainChange(row)"
          v-hasPermi="['api:merchant:setMain']"
          >设置为主推</el-button
        >
        <el-button
          type="primary"
          link
          icon="Plus"
          @click="addMoney(row)"
          v-hasPermi="['api:merchant:addMoney']"
          >加款</el-button
        >
        <el-button
          type="primary"
          link
          icon="Edit"
          @click="change(row)"
          v-hasPermi="['api:merchant:change']"
          >编辑</el-button
        >
        <!-- <el-button
          type="primary"
          link
          icon="Edit"
          @click="resertPwd(row)"
          v-hasPermi="['api:merchant:resertPwd']"
          >重置密码</el-button
        > -->
        <el-button
          type="primary"
          link
          icon="Edit"
          @click="changeCredit(row)"
          v-hasPermi="['api:merchant:changeCredit']"
          >修改授信</el-button
        >
        <!-- <el-button
          type="primary"
          link
          icon="Delete"
          @click="del(row)"
          v-hasPermi="['api:merchant:del']"
          >删除</el-button
        > -->
      </template>
    </x-table>
    <pagination
      v-show="info.total > 0"
      :total="info.total"
      v-model:page="searchInfo.pageNum"
      v-model:limit="searchInfo.pageSize"
      @pagination="getInfo"
    />
    <Dialog
      width="30%"
      :title="dialogConfig.title"
      v-model:isShowDialog="isShowDialog"
      @confirm="submit"
    >
      <Form ref="formRef" v-bind="dialogConfig.formConfig"> </Form>
    </Dialog>
    <Dialog
      width="30%"
      :title="dialogConfig2.title"
      v-model:isShowDialog="isShowDialog2"
      @confirm="submit2"
    >
      <Form ref="formRef2" v-bind="dialogConfig2.formConfig"> </Form>
    </Dialog>

    <el-dialog
      v-model="isShowAddMoney"
      title="加款"
      width="30%"
      destroy-on-close
      center
    >
      <el-form
        ref="addMoney"
        :model="addMoneyInfo"
        :rules="addMoneyinfoRules"
        label-width="78px"
      >
        <el-form-item label="商户" prop="name">
          <el-input v-model="addMoneyInfo.name" disabled />
        </el-form-item>
        <el-form-item label="余额" prop="balance">
          <el-input v-model="addMoneyInfo.balance" disabled />
        </el-form-item>
        <el-form-item label="授信" prop="credit">
          <el-input v-model="addMoneyInfo.credit" disabled />
        </el-form-item>
        <el-form-item label="加款账号" prop="money_id">
          <el-select v-model="addMoneyInfo.money_id">
            <el-option
              v-for="item in moneyConfig"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="加款金额" prop="addMoneyVal">
          <el-input v-model="addMoneyInfo.addMoneyVal" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="addMoneyInfo.remark" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="isShowAddMoney = false">取消</el-button>
          <el-button type="primary" @click="submitAddMoney"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { propList, formItems, dialogConfig, dialogConfig2 } from "./config";
import { getTempList } from "@/api/channel";
import { getMoneySet } from "@/api/common";
import {
  getList,
  getAllGroup,
  add,
  change,
  del,
  change_credit,
  addMoney,
  resertPwd,
  inManage,
  setSharePoster,
  setPay,
  setMain
} from "@/api/platform/merchant";
import { getToken, setTokenBykey, removeToken } from "@/utils/auth";
import { getAllList as listAllCustomer } from "@/api/platform/merchant";

export default {
  name: "merchantlistindex",
  data() {
    return {
      isShowAddMoney: false,
      dialogConfig,
      dialogConfig2,
      curItem: {},
      isLoading: false,
      showSearch: true,
      isShowDialog: false,
      isShowDialog2: false,
      addMoneyInfo: {},
      addMoneyinfoRules: {
        money_id: [{ required: true, message: "请选择", trigger: "blur" }],
        addMoneyVal: [{ required: true, message: "请输入", trigger: "blur" }],
      },
      propList,
      formItems,
      info: {},
      moneyConfig: [],
      customerList:[],
      searchInfo: {
        pageNum: 1,
        pageSize: 10,
        created_at: this.getTimeFilterDefault(true),
      },
    };
  },
  computed: {},
  created() {
    this.init();
  },
  mounted() {},
  methods: {
    init() {
      this.getInfo();
      this.getAllTempList();
      this.getAllGroup();
      this.getMoneySet();
      this.getCustomerList();
    },
    getCustomerList() {
      listAllCustomer().then((response) => {
        this.customerList = response.data;
      });
    },
    async getMoneySet() {
      const { data } = await getMoneySet();
      this.moneyConfig = data;
    },
    async getInfo() {
      const params = { ...this.searchInfo };
      const { data } = await getList(params);
      this.info = data;
    },
    async getAllGroup() {
      const { data } = await getAllGroup();
      // 赋值表单
      this.dialogConfig.formConfig.formItems.forEach((item) => {
        if (item.prop == "group_id") {
          item.options = data;
        }
      });
    },
    async manage(item) { 
      // 本地存储merchant——id
      setTokenBykey(`member_id`, item.id);
      const url = `${window.location.origin}${this.$router.resolve({
        name: "mpauthindex",
        params: {id:1},
      }).href}`;
 
      // 打开新窗口
      window.open(url, '_blank');
      // 
      // const { data } = await inManage(item.id)
      // console.log(data)
      // // 
      // setTokenBykey(`${data.id}:token`, data.token);
      // // 跳转
      // const url = import.meta.env.VITE_APP_ENV == "development"
      //   ? import.meta.env.VITE_APP_BASE_API
      //   : window.location.origin;
      // // window.open(`${url}`, "_black");
      // window.open(`./${data.id}`, "_black");
      // http://localhost:1025/admin/merchant/merchantList
    },
    async getAllTempList() {
      getTempList().then((res) => {
        console.log(res);
        const data = res.data;
        const templateList = [];
        for (let key in data) {
          templateList.push({
            code: key,
            name: data[key]["name"],
            setting: data[key]["setting"],
          });
        }
        // 赋值表单
        this.dialogConfig.formConfig.formItems.forEach((item) => {
          if (item.prop == "channel_code") {
            item.options = templateList;
          }
        });
        // channelTempList = templateList;
        // console.log(channelTempList.value);
      });
    },
    addMoney(item) {
      this.addMoneyInfo = { ...item };
      this.addMoneyInfo.name = `(${item.username}${item.nickname})`;
      this.addMoneyInfo.remark = "";
      this.isShowAddMoney = true;
    },
    resertPwd(item) {
      this.$confirm("确定要重置密码吗?", "提示", {
        cancelButtonText: "取消",
        confirmButtonText: "确定",
        type: "warning",
      })
        .then(async () => {
          await resertPwd(item.id);
          this.$message.success("操作成功,新密码:123456");
          this.getInfo();
        })
        .catch(() => {});
    },
    submitAddMoney() {
      // 提交加款请求
      this.$refs.addMoney.validate(async (valid) => {
        if (valid) {
          console.log(this.addMoneyInfo);
          const params = {
            id: this.addMoneyInfo.id,
            money: this.addMoneyInfo.addMoneyVal,
            money_id: this.addMoneyInfo.money_id,
            remark: this.addMoneyInfo.remark,
          };
          await addMoney(params);
          this.$message.success("操作成功");
          this.getInfo();
          this.isShowAddMoney = false;
        }
      });
    },
    changeCredit(item) {
      this.isShowDialog2 = true;
      this.dialogConfig2.formConfig.formData = { ...item };
    },
    submit2() {
      this.$refs.formRef2.validate(async (valid) => {
        if (valid) {
          const params = { ...this.dialogConfig2.formConfig.formData };
          await change_credit(params);
          this.$message.success("操作成功");
          this.isShowDialog2 = false;
          this.getInfo();
        }
      });
    },
    submit() {
      // console.log(this.dialogConfig.formConfig.formData);
      // return false;
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          const params = { ...this.dialogConfig.formConfig.formData };
          if (params.id) {
            await change(params);
          } else {
            await add(params);
            this.getCustomerList()
          }
          this.isShowDialog = false;
          this.getInfo();
          this.$message.success("操作成功");
        }
      });
    },
    resetSearch() {
      this.searchInfo = this.$options.data.call(this).searchInfo;
      this.searchInfo.created_at = this.getTimeFilterDefault(true);
      this.getInfo();
    },
    goSearch() {
      // 重置时间
      this.getInfo();
    },
    add() {
      this.dialogConfig.formConfig.formData = {};
      this.dialogConfig.formConfig.formItems.forEach((i) => {
        if (i.prop == "password") {
          i.isHide = false;
        }
      });
      this.isShowDialog = true;
    },
    change(item) {
      // 修改
      this.dialogConfig.formConfig.formData = { ...item };
      // 取消密码
      // this.dialogConfig.formConfig.formData.password = ""
      this.dialogConfig.formConfig.formItems.forEach((i) => {
        if (i.prop == "password") {
          i.isHide = true;
        }
      });
      this.isShowDialog = true;
    },
    // async setPay(e, item) {
    //   console.log(e, item)
    //   await setSharePoster({
    //     id:item.id,
    //     share_sys_user_id:e
    //   })
    //   this.getInfo()
    //   this.$message('修改成功')
    // },
    
    async setPoster(e, item) {
      console.log(e, item)
      await setSharePoster({
        id:item.id,
        share_sys_user_id:e
      })
      this.getInfo()
      this.$message('修改成功')
    },
    async mainChange(item) {
      // console.log(e, item)
      await setMain({
        id:item.id,
        // is_main:e
      })
      this.getInfo()
      this.$message('修改成功')
    },
    del(item) {
      // 删除
      this.$confirm("确定要删除吗?", "提示", {
        cancelButtonText: "取消",
        confirmButtonText: "确定",
        type: "warning",
      })
        .then(async () => {
          await del(item.id);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.getInfo();
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="scss" scoped>
/* @media screen and (max-width: 500px) {
  :deep(.el-dialog) {
    width: 300px !important;
    :deep(.el-dialog__body) {
      padding: 10px 20px !important;
      :deep(.el-form-item__label) {
        width: 68px !important;
      }
      :deep(.el-select),
      :deep(.el-input) {
        width: 180px !important;
      }
    }
  }
} */
</style>
